package com.coderside.fragment.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	/** 端口号 */
	public static final int PORT = 9999;

	public static void main(String[] args) {
		System.out.println("服务器...\n");
		Server ser = new Server();
		ser.sock();
	}

	public void sock() {
		try {
			ServerSocket server = new ServerSocket(PORT);
			while (true) {
				// 一旦有堵塞, 则表示服务器与客户端获得了连接
				Socket client = server.accept();
				// 处理这次连接
				new PServer(client);
			}
		} catch (Exception e) {
			System.out.println("服务器异常: " + e.getMessage());
		}
	}

	private class PServer implements Runnable {

		private Socket socket;

		public PServer(Socket sock) {
			socket = sock;
			new Thread(this).start();
		}

		public void run() {
			try {

				// 向客户端发送数据
				OutputStream os = socket.getOutputStream();
				// 读取客户端数据
				byte[] b = new byte[8192];
				// 读取客户端数据
				System.out.println("客户端发过来的内容: ");
				new ReadThread(socket.getInputStream());
				// 发送键盘输入的一行
				String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
				BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
				bw.write(s);
				bw.newLine();
				bw.flush();
				bw.close();

			} catch (Exception e) {
				System.out.println("服务器 run 异常: " + e.getMessage());
			}
		}
	}

	private class ReadThread implements Runnable {
		private InputStream in;

		ReadThread(InputStream is) {
			this.in = is;
			new Thread(this).start();
		}

		public void run() {
			try {
				int mimeType = in.read();
				if (mimeType == 0) {
					String line = null;
					BufferedReader br = new BufferedReader(new InputStreamReader(in));
					while ((line = br.readLine()) != null && !line.equals("exit")) {
						System.out.println(line);
					}
				} else if (mimeType == 1) {
					writeFile(in, "zz.zip");
				}

			} catch (IOException e) {
				//				e.printStackTrace();
			}
		}

		private void writeFile(InputStream in, String outFileName) {
			try {
				FileOutputStream fos = new FileOutputStream(new File(outFileName));
				byte[] b = new byte[1024 * 10];
				int len = 0;
				while ((len = in.read(b)) != -1) {
					if (len < b.length) {
						byte[] b2 = new byte[len];
						System.arraycopy(b, 0, b2, 0, len);
						fos.write(b2);
						fos.flush();
					} else {
						fos.write(b);
						fos.flush();
					}
				}
				fos.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}